import { AddOrderItemType, CommodityListType, OrderItemType } from "@Tea/model"
import { AppTokenObj } from "../dao/AppToken"
import { renderSelectParam, renderSelectSql } from "../utils/renderSql"
import { ReposBase } from "./RepoBase"

export class OrderItemRepository extends ReposBase {
  private static inst: OrderItemRepository

  public static getInstance() {
    if (!OrderItemRepository.inst) {
      OrderItemRepository.inst = new OrderItemRepository()
    }

    return OrderItemRepository.inst
  }

  addOrderItem(params: AddOrderItemType) {
    const sql = `INSERT into order_items(order_id, tea_id, order_number) VALUES('${params.orderId}', ${params.teaId}, ${params.orderNumber})`
    return this.insert(sql)
  }

  cancelOrderItem(orderId: string) {
    return this.delete(`DELETE FROM order_items WHERE order_id = '${orderId}'`)
  }

  getItemByOrderId(orderId: string) {
    const config: renderSelectParam = {
      database: [
        { name: 'order_items', aliasName: "i" },
        { name: "commodities", aliasName: 'c' },
        { name: "tea_types", aliasName: 't' }
      ],
      returnFeild: [
        { name: "i.tea_id", aliasName: "teaId" },
        { name: 'c.tea_name', aliasName: 'teaName' },
        "cover",
        { name: 't.type_name', aliasName: 'typeName' },
        { name: 'c.tea_type', aliasName: 'teaType' },
        { name: 'i.order_number', aliasName: 'orderNumber' },
        "price",
        { name: 'i.id', aliasName: 'orderItemId' },
      ],
      where: [
        { key: 'c.tea_type', sqlVal: 't.type_id', isDatabase: true },
        { key: 'i.tea_id', sqlVal: 'c.tea_id', isDatabase: true },
        { key: 'i.order_id', sqlVal: orderId}
      ],
      like:[]
    }

    const sql = renderSelectSql(config)

    return this.query<OrderItemType>(sql)
  }
}